/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#ifndef XERNP_GRIDNODE_HPP
#define XERNP_GRIDNODE_HPP

#include "Xern/IMetaverseNode.hpp"
#include "Packet.hpp"
#include "Session.hpp"

namespace XernProtocol
{
	using namespace Xern;

	class GridNode: public IMetaverseNode
	{
	public:
		static const posix_time::time_duration NetworkThreadInterval;
		static const posix_time::time_duration PacketResendInterval;
		static const posix_time::time_duration KeepAliveInterval;
		static const posix_time::time_duration SessionTimeout;
		static const posix_time::time_duration PacketDuplicationTolerance;
		static const posix_time::ptime PacketEpoch;
		static const posix_time::time_duration ConnectTimeout;
		static const int ConnectTries;
		static const int MaxResendCount;

		GridNode();
		~GridNode();

		virtual void Initialize();
		virtual void Shutdown();

	protected:
		typedef std::map<u32, boost::shared_ptr<Session> > LocalSessions;
		typedef std::map<RemoteSessionId, boost::shared_ptr<Session> > RemoteSessions;

		// Returns a new packet sequence number.
		u32 GetPacketSequence();

		// Returns a new session id.
		u32 GetSessionSequence();

		// Session events.
		virtual void Session_Opened(boost::shared_ptr<Session> session);
		virtual void Session_Timeout(boost::shared_ptr<Session> session);
		virtual void Session_Closed(boost::shared_ptr<Session> session);

		// Session handling.
		void Session_Open(Packet &packet, const udp::endpoint &endpoint);
		void Session_Close(boost::shared_ptr<Session> session);
		void Session_ReceivePacket(boost::shared_ptr<Session> session, Packet &packet);
		void Session_Think(boost::shared_ptr<Session> session);
		void Session_Send(boost::shared_ptr<Session> session);
		void Session_Resend(boost::shared_ptr<Session> session);
		void Session_Acknowledge(boost::shared_ptr<Session> session);
		void Session_KeepAlive(boost::shared_ptr<Session> session);
		void Session_Clean(boost::shared_ptr<Session> session);
		boost::shared_ptr<Session> ConnectSession(const udp::endpoint &endpoint);
		void DisconnectSession(boost::shared_ptr<Session> session, bool wait);

		// Threading.
		void SendThread();
		void ReceiveThread();

		// Network events.
		void OnPacketReceived(const boost::system::error_code &err, size_t size);
		void ProcessReceivedPacket(Packet &packet, udp::endpoint &endpoint);

		// Local sessions map.
		LocalSessions localSessions;

		// Remote sessions map.
		RemoteSessions remoteSessions;

		// I/O service.
		boost::asio::io_service ioService;

		// Node socket.
		udp::socket nodeSocket;

		// Node mutex.
		boost::mutex nodeMutex;

		// Send thread.
		boost::thread sendThread;

		// Receive thread.
		boost::thread receiveThread;

		// Received packet.
		Packet receivedPacket;

		// Received packet endpoint.
		udp::endpoint receiveEndpoint;

		// Packet sequence number.
		u32 packetSequence;

		// Packet sequence number mutex.
		boost::mutex packetSequenceMutex;

		// Session sequence number.
		u32 sessionSequence;

		// Session sequence number mutex.
		boost::mutex sessionSequenceMutex;

		// Default message decoder.
		boost::shared_ptr<IMessageDecoder> defaultMessageDecoder;

		// Connection accepted/refuse condition variable.
		boost::condition_variable connectionCondition;

		// Disconection complete.
		boost::condition_variable disconnectionCondition;

		// Node is initialized.
		bool isInitialized;

		// Node is shutting down.
		bool isShuttingDown;
	};
};

#endif //XERNP_GRIDNODE_HPP
